﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using NetworkManagement;

namespace LorraineSec.MessageLib.Messages
{
    public sealed class AuthRequestMessage : EncryptedMessage
    {
        #region Format Constants
        /*
         * Format:
         *          1                 1            x          y
         * | Username Length | PW Hash Length | Username | PW Hash |
         * 
         */

        //Lengths
        private const int ENC_USERNAMELEN_LENGTH = 1;
        private const int ENC_PWHASHLEN_LENGTH = 1;

        //Offsets
        private const int ENC_USERNAMELEN_OFFSET = 0;
        private const int ENC_PWHASHLEN_OFFSET = ENC_USERNAMELEN_OFFSET + ENC_USERNAMELEN_LENGTH;
        private const int ENC_USERNAME_OFFSET = ENC_PWHASHLEN_OFFSET + ENC_PWHASHLEN_LENGTH;

        //Known Length
        private const int ENC_KNOWN_LENGTH = ENC_USERNAMELEN_LENGTH + ENC_PWHASHLEN_LENGTH;
        #endregion

        public string Username;
        public string PasswordHash;

        public AuthRequestMessage()
        {
            init();
        }

        public AuthRequestMessage(byte[] bytes)
            : base(bytes)
        {
            init();
            decode();
        }

        private void init()
        {
            MessageID = (ushort)LorraineSecMessageFactory.MessageID.AUTH_REQUEST;
        }

        public override void decrypt(CryptoManager crypt)
        {
            //Decrypt byte array
            base.decrypt(crypt);
            //Decode byte array
            Username = Bytes.getString(encData, ENC_USERNAME_OFFSET, Bytes.getByte(encData, ENC_USERNAMELEN_OFFSET));
            PasswordHash = Bytes.getString(encData, ENC_USERNAME_OFFSET + Username.Length, Bytes.getByte(encData, ENC_PWHASHLEN_OFFSET));
        }

        public override void encrypt(CryptoManager crypt)
        {
            //Encode Byte Array
            encData = new byte[ENC_KNOWN_LENGTH + Username.Length + PasswordHash.Length];
            Bytes.setValue(encData, ENC_USERNAMELEN_OFFSET, (byte)Username.Length);
            Bytes.setValue(encData, ENC_PWHASHLEN_OFFSET, (byte)PasswordHash.Length);
            Bytes.setValue(encData, ENC_USERNAME_OFFSET, Username);
            Bytes.setValue(encData, ENC_USERNAME_OFFSET + Username.Length, PasswordHash);
            //Encrypt Byte Array
            base.encrypt(crypt);
        }
    }
}
